/*
 * Code for blog.techhead.biz
 * Distributed under BSD-style license
 */

package biz.techhead.qbpos;

import java.io.*;

import java.nio.CharBuffer;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author jonathan
 */
public class QBPOSXMLRPServlet extends HttpServlet {
   
    @Override
    public void init()
    throws ServletException {
        ServletConfig sc = getServletConfig();
        String rpName = sc.getInitParameter("com.jackwrapit.qbpos.RequestProcessor");
        if (rpName == null) {
            RequestProcessorCOMImpl rp = new RequestProcessorCOMImpl();
            rp.setAppId(sc.getInitParameter("appId"));
            rp.setAppName(sc.getInitParameter("appName"));
            rp.setQBComputerName(sc.getInitParameter("QBComputerName"));
            rp.setQBCompanyDataName(sc.getInitParameter("QBCompanyDataName"));
            rp.setQBCompanyDataVersion(sc.getInitParameter("QBCompanyDataVersion"));
            rp.setQBPracticeMode("true".equals(sc.getInitParameter("QBPracticeMode")));
            qbposXMLRP = rp;
        } else {
            try {
                Context initCtx = new InitialContext();
                Context envCtx = (Context) initCtx.lookup("java:comp/env");
                qbposXMLRP = (RequestProcessor) envCtx.lookup(rpName);
            } catch (NamingException ex) {
                throw new ServletException(ex);
            }
        }
    }

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        if ("reinit".equals(request.getParameter("action"))) {
            init();
        } else {
            super.doGet(request, response);
        }
    }
    
    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        String requestXML = readAll(request); // Read in the XML request as a String
        String responseXML = qbposXMLRP.processRequest(requestXML, // Wait up to 10 seconds for the response.
                new SimpleResponseProcessor()).waitForResponseXML(10*1000L);
        
        // Return the response
        response.setContentType("application/qbpos+xml;charset=utf-8");
        response.setContentLength(responseXML.length());
        PrintWriter out = response.getWriter();
        try {
            out.print(responseXML);
        } finally { 
            out.close();
        }
    }

    private String readAll(HttpServletRequest request) throws IOException {
        Reader in = request.getReader();
        try {
            StringBuffer sb = new StringBuffer(2*1024);
            CharBuffer cb = CharBuffer.allocate(2*1024);
            while (in.read(cb) != -1) {
                sb.append(cb.flip());
                cb.rewind();
            }
            return sb.toString();
        } finally {
            in.close();
        }
    }

    /** 
    * Returns a short description of the servlet.
    */
    @Override
    public String getServletInfo() {
        return "Process a XML request for QBPOS.";
    }
    
    private RequestProcessor qbposXMLRP;
}
